#!/usr/bin/env python3
"""
MACD策略优化系统 - 综合演示脚本
展示所有优化功能的实际效果
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from stock_analyzer import StockAnalyzer
from backtesting_system import BacktestingSystem
from divergence_detector import DivergenceDetector

class ComprehensiveDemo:
    """
    综合演示类
    展示MACD策略优化系统的完整功能
    """
    
    def __init__(self):
        """初始化演示系统"""
        self.test_symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'NVDA']
        self.results = {}
    
    def run_complete_demo(self):
        """
        运行完整的演示
        """
        print("=" * 80)
        print("MACD策略优化系统 - 综合演示")
        print("=" * 80)
        print()
        
        # 1. 展示基础分析功能
        print("1. 基础MACD分析功能演示")
        print("-" * 50)
        self.demo_basic_analysis()
        
        # 2. 展示改进的背离检测
        print("\n2. 改进的背离检测算法演示")
        print("-" * 50)
        self.demo_divergence_detection()
        
        # 3. 展示动态权重调整
        print("\n3. 动态权重调整系统演示")
        print("-" * 50)
        self.demo_dynamic_weighting()
        
        # 4. 展示回测验证系统
        print("\n4. 回测验证系统演示")
        print("-" * 50)
        self.demo_backtesting_system()
        
        # 5. 生成综合报告
        print("\n5. 综合性能报告")
        print("-" * 50)
        self.generate_comprehensive_report()
        
        print("\n" + "=" * 80)
        print("演示完成！")
        print("=" * 80)
    
    def demo_basic_analysis(self):
        """
        演示基础MACD分析功能
        """
        symbol = 'AAPL'
        print(f"分析股票: {symbol}")
        
        try:
            # 创建分析器
            analyzer = StockAnalyzer(symbol, period="3mo")
            
            # 获取数据
            if not analyzer.fetch_data():
                print(f"无法获取 {symbol} 的数据")
                return
            
            # 计算MACD
            macd_result = analyzer.calculate_macd()
            if not macd_result['success']:
                print(f"MACD计算失败: {macd_result['message']}")
                return
            
            # 检测交叉信号
            crossover_result = analyzer.detect_macd_crossover()
            
            print(f"✓ 数据获取成功，共 {len(analyzer.data)} 个交易日")
            print(f"✓ MACD计算完成")
            
            # 显示当前信号
            if crossover_result['golden_cross']['detected']:
                quality = crossover_result['golden_cross']['quality']
                print(f"✓ 检测到金叉信号 - 质量: {quality}")
                print(f"  位置评分: {crossover_result['golden_cross']['position_score']:.1f}")
                print(f"  共振评分: {crossover_result['golden_cross']['resonance_score']:.1f}")
                print(f"  成交量评分: {crossover_result['golden_cross']['volume_score']:.1f}")
                print(f"  时效评分: {crossover_result['golden_cross']['timeliness_score']:.1f}")
            
            if crossover_result['death_cross']['detected']:
                risk = crossover_result['death_cross']['risk_level']
                print(f"⚠ 检测到死叉信号 - 风险: {risk}")
                print(f"  位置风险: {crossover_result['death_cross']['position_risk']:.1f}")
                print(f"  动量风险: {crossover_result['death_cross']['momentum_risk']:.1f}")
                print(f"  成交量风险: {crossover_result['death_cross']['volume_risk']:.1f}")
                print(f"  时效风险: {crossover_result['death_cross']['timeliness_risk']:.1f}")
            
            if crossover_result['pre_golden_cross']['detected']:
                print(f"📈 检测到预金叉信号 - 概率: {crossover_result['pre_golden_cross']['probability']:.1f}%")
            
            self.results[symbol] = {
                'basic_analysis': crossover_result,
                'data_points': len(analyzer.data)
            }
            
        except Exception as e:
            print(f"分析过程中出现错误: {str(e)}")
    
    def demo_divergence_detection(self):
        """
        演示改进的背离检测算法
        """
        print("测试背离检测算法...")
        
        # 创建背离检测器
        divergence_detector = DivergenceDetector(lookback_period=60)
        
        # 使用AAPL数据进行测试
        symbol = 'AAPL'
        analyzer = StockAnalyzer(symbol, period="6mo")
        
        try:
            if analyzer.fetch_data() and analyzer.calculate_macd()['success']:
                # 获取最近60天的数据
                recent_data = analyzer.data.tail(60)
                macd_data = analyzer.macd_data.tail(60)
                
                price_series = recent_data['Close']
                macd_series = macd_data['MACD']
                histogram_series = macd_data['Histogram']
                
                # 执行背离检测
                divergence_result = divergence_detector.detect_divergences(
                    price_series, macd_series, histogram_series
                )
                
                print(f"✓ 背离检测完成 - {symbol}")
                
                # 显示看涨背离结果
                bullish_div = divergence_result['bullish_divergences']
                if bullish_div['any_detected']:
                    print("📈 检测到看涨背离:")
                    if bullish_div['classic']['detected']:
                        strength = bullish_div['classic']['strength']
                        print(f"  - 经典看涨背离 (强度: {strength:.2f})")
                    if bullish_div['hidden']['detected']:
                        strength = bullish_div['hidden']['strength']
                        print(f"  - 隐性看涨背离 (强度: {strength:.2f})")
                    if bullish_div['histogram']['detected']:
                        strength = bullish_div['histogram']['strength']
                        print(f"  - 柱状图看涨背离 (强度: {strength:.2f})")
                
                # 显示看跌背离结果
                bearish_div = divergence_result['bearish_divergences']
                if bearish_div['any_detected']:
                    print("📉 检测到看跌背离:")
                    if bearish_div['classic']['detected']:
                        strength = bearish_div['classic']['strength']
                        print(f"  - 经典看跌背离 (强度: {strength:.2f})")
                    if bearish_div['hidden']['detected']:
                        strength = bearish_div['hidden']['strength']
                        print(f"  - 隐性看跌背离 (强度: {strength:.2f})")
                    if bearish_div['histogram']['detected']:
                        strength = bearish_div['histogram']['strength']
                        print(f"  - 柱状图看跌背离 (强度: {strength:.2f})")
                
                # 显示整体背离强度
                strength = divergence_result['divergence_strength']
                print(f"整体背离评估:")
                print(f"  方向: {strength['direction']}")
                print(f"  强度: {strength['overall_strength']:.2f}")
                print(f"  可靠性: {strength['reliability']}")
                print(f"  置信度: {strength['confidence']:.2f}")
                
                # 保存结果
                if symbol in self.results:
                    self.results[symbol]['divergence_analysis'] = divergence_result
                else:
                    self.results[symbol] = {'divergence_analysis': divergence_result}
            
        except Exception as e:
            print(f"背离检测过程中出现错误: {str(e)}")
    
    def demo_dynamic_weighting(self):
        """
        演示动态权重调整系统
        """
        print("测试动态权重调整系统...")
        
        symbol = 'TSLA'  # 使用波动性较大的股票
        analyzer = StockAnalyzer(symbol, period="3mo")
        
        try:
            if analyzer.fetch_data() and analyzer.calculate_macd()['success']:
                # 检测交叉信号（会自动使用动态权重）
                crossover_result = analyzer.detect_macd_crossover()
                
                print(f"✓ 动态权重系统测试完成 - {symbol}")
                
                # 显示市场状态分析结果
                if hasattr(analyzer, 'market_state_analyzer') and analyzer.market_state_analyzer:
                    market_state = analyzer.market_state_analyzer.analyze_market_state()
                    print(f"市场状态分析:")
                    print(f"  趋势状态: {market_state['trend_state']}")
                    print(f"  波动性状态: {market_state['volatility_state']}")
                    print(f"  成交量状态: {market_state['volume_state']}")
                    print(f"  动量状态: {market_state['momentum_state']}")
                    print(f"  整体环境: {market_state['overall_environment']}")
                    
                    # 显示动态权重
                    dynamic_weights = analyzer.market_state_analyzer._get_dynamic_weights(market_state)
                    print(f"动态权重调整:")
                    print(f"  位置权重: {dynamic_weights['position']:.2f}")
                    print(f"  共振权重: {dynamic_weights['resonance']:.2f}")
                    print(f"  成交量权重: {dynamic_weights['volume']:.2f}")
                    print(f"  时效权重: {dynamic_weights['timeliness']:.2f}")
                
                # 显示信号质量（已应用动态权重）
                if crossover_result['golden_cross']['detected']:
                    print(f"金叉信号质量 (动态权重调整后): {crossover_result['golden_cross']['quality']}")
                
                if crossover_result['death_cross']['detected']:
                    print(f"死叉风险等级 (动态权重调整后): {crossover_result['death_cross']['risk_level']}")
                
                # 保存结果
                if symbol in self.results:
                    self.results[symbol]['dynamic_weighting'] = crossover_result
                else:
                    self.results[symbol] = {'dynamic_weighting': crossover_result}
            
        except Exception as e:
            print(f"动态权重测试过程中出现错误: {str(e)}")
    
    def demo_backtesting_system(self):
        """
        演示回测验证系统
        """
        print("运行回测验证系统...")
        
        symbol = 'MSFT'
        
        try:
            # 创建回测系统
            backtester = BacktestingSystem(symbol, period="1y")
            
            # 运行回测
            backtest_result = backtester.run_backtest()
            
            if backtest_result['success']:
                metrics = backtest_result['metrics']
                
                print(f"✓ 回测完成 - {symbol}")
                print(f"回测期间: {backtest_result['start_date']} 至 {backtest_result['end_date']}")
                print(f"交易次数: {metrics['total_trades']}")
                print(f"胜率: {metrics['win_rate']:.1f}%")
                print(f"总收益率: {metrics['total_return']:.1f}%")
                print(f"年化收益率: {metrics['annualized_return']:.1f}%")
                print(f"夏普比率: {metrics['sharpe_ratio']:.2f}")
                print(f"最大回撤: {metrics['max_drawdown']:.1f}%")
                print(f"平均持仓天数: {metrics['avg_holding_days']:.1f}")
                
                # 按信号质量分析
                quality_analysis = backtest_result.get('quality_analysis', {})
                if quality_analysis:
                    print(f"按信号质量分析:")
                    for quality, stats in quality_analysis.items():
                        if stats['trades'] > 0:
                            print(f"  {quality}质量信号: 胜率 {stats['win_rate']:.1f}%, 平均收益 {stats['avg_return']:.1f}%")
                
                # 保存结果
                if symbol in self.results:
                    self.results[symbol]['backtesting'] = backtest_result
                else:
                    self.results[symbol] = {'backtesting': backtest_result}
            else:
                print(f"回测失败: {backtest_result.get('message', '未知错误')}")
        
        except Exception as e:
            print(f"回测过程中出现错误: {str(e)}")
    
    def generate_comprehensive_report(self):
        """
        生成综合性能报告
        """
        print("生成综合性能报告...")
        
        if not self.results:
            print("没有可用的分析结果")
            return
        
        # 统计信息
        total_symbols = len(self.results)
        successful_analyses = 0
        total_signals = 0
        high_quality_signals = 0
        
        print(f"分析概览:")
        print(f"  测试股票数量: {total_symbols}")
        
        for symbol, data in self.results.items():
            print(f"\n{symbol} 分析结果:")
            
            # 基础分析结果
            if 'basic_analysis' in data:
                successful_analyses += 1
                basic = data['basic_analysis']
                
                if basic['golden_cross']['detected']:
                    total_signals += 1
                    quality = basic['golden_cross']['quality']
                    print(f"  ✓ 金叉信号: {quality}")
                    if quality == 'high':
                        high_quality_signals += 1
                
                if basic['death_cross']['detected']:
                    risk = basic['death_cross']['risk_level']
                    print(f"  ⚠ 死叉信号: {risk}风险")
                
                if basic['pre_golden_cross']['detected']:
                    prob = basic['pre_golden_cross']['probability']
                    print(f"  📈 预金叉: {prob:.1f}%概率")
            
            # 背离分析结果
            if 'divergence_analysis' in data:
                div_data = data['divergence_analysis']
                if div_data['has_significant_divergence']:
                    direction = div_data['divergence_strength']['direction']
                    confidence = div_data['divergence_strength']['confidence']
                    print(f"  🔄 显著背离: {direction} (置信度: {confidence:.2f})")
            
            # 回测结果
            if 'backtesting' in data:
                backtest = data['backtesting']
                if backtest['success']:
                    metrics = backtest['metrics']
                    print(f"  📊 回测结果: 胜率 {metrics['win_rate']:.1f}%, 夏普比率 {metrics['sharpe_ratio']:.2f}")
        
        # 整体统计
        print(f"\n整体统计:")
        print(f"  成功分析率: {successful_analyses}/{total_symbols} ({successful_analyses/total_symbols*100:.1f}%)")
        if total_signals > 0:
            print(f"  高质量信号比例: {high_quality_signals}/{total_signals} ({high_quality_signals/total_signals*100:.1f}%)")
        
        # 系统优化效果总结
        print(f"\n系统优化效果:")
        print(f"  ✓ 动态权重调整: 根据市场状态自适应调整评分权重")
        print(f"  ✓ 改进背离检测: 区分经典、隐性和柱状图背离，提高检测准确性")
        print(f"  ✓ 时效性优化: 优先成熟信号，降低过早入场风险")
        print(f"  ✓ 质量验证: 多维度交叉验证，过滤噪音信号")
        print(f"  ✓ 回测验证: 客观量化策略表现，提供数据支撑")

def main():
    """
    主函数
    """
    try:
        # 创建并运行演示
        demo = ComprehensiveDemo()
        demo.run_complete_demo()
        
    except KeyboardInterrupt:
        print("\n演示被用户中断")
    except Exception as e:
        print(f"演示过程中出现错误: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()